//
//  ClueViewController.m
//  OCPB
//
//  Created by Siroj Chongkolwanont on 7/17/56 BE.
//  Copyright (c) 2556 Siroj Chongkolwanont. All rights reserved.
//

#import "ClueViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "Document.h"
#import "DocumentType.h"
#import "UIDeleteButton.h"
#import "UIDocTypeTextField.h"

@interface ClueViewController ()

@end

@implementation ClueViewController

@synthesize detailView;

@synthesize subjectText;
@synthesize nameReqText;
@synthesize surNameReqText;
@synthesize telText;
@synthesize emailText;
@synthesize compName;
@synthesize scrollView;
@synthesize fileTable;
@synthesize docTypePickerView;
@synthesize localSpiner;
@synthesize docTypeTxt;


UITextField* currentTextField;
UITextView* currentTextView;

NSMutableArray* documentArray;
NSMutableArray* documentTypeArray;
NSMutableArray* docTypesPickerArray;

DocumentType* currentDocType;
Document* currentDoc;

UIButton* currentDocButton;


UIDocTypeTextField *currentTextFileType;

UIActionSheet* aDocTypeSheet;


bool isDelete = false;


- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"แจ้งเบาะเเส"
                                                      message:@"ไม่สามารถเชื่อมต่ออินเตอร์เน็ทได้ กรุณาตรวจสอบการตั้งค่าที่โทรศัพท์"
                                                     delegate:nil
                                            cancelButtonTitle:@"OK"
                                            otherButtonTitles:nil];
    [message show];
}

id jsonObjectFromUrlString(NSString *urlString);


-(BOOL)textFieldShouldReturn:(UITextField*)textField;
{
    
    if(textField == subjectText)
    {
        [detailView becomeFirstResponder];
    }
    
    if(textField == telText)
    {
        [textField resignFirstResponder];
    }
    
    if(textField == compName)
    {
        [emailText becomeFirstResponder];
        
    }
    
    if(textField == emailText )
    {
        [telText becomeFirstResponder];
    }

    
    return NO; // We do not want UITextField to insert line-breaks.
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return  1;
}

- (void)doneTapped
{
    [currentTextField resignFirstResponder];
    
    if (currentTextField.tag == 102)
    {
       // currentTextField.text = currentDocType.document_name;
        
//        Document* doc = currentDoc;
    }
    
    NSInteger nextTag = currentTextField.tag + 1;
    // Try to find next responder
    UIResponder* nextResponder = [currentTextView.superview viewWithTag:nextTag];
    if (nextResponder) {
        // Found next responder, so set it.
        // [nextResponder becomeFirstResponder];
    }
    
}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    // The number of rows in the UIPickerView
    //return [pickerData count];
    
        
        return [documentTypeArray count];
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component;
{

        return ((DocumentType*)documentTypeArray[row]).document_name;
    
}


- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    // whatever you want to happen when a row is selected.
    
    
    DocumentType* type = documentTypeArray[row];
    
    currentDocType = type;


    
    if(documentArray.count > 0)
    {
        UIDocTypeTextField* docTypeField = (UIDocTypeTextField*)currentTextField;

        Document* doc = documentArray[docTypeField.row ];

        doc.Document_id = type.document_id;
        doc.Document_TypeName = type.document_name;
        doc.Document_index = row;
    }
    
    currentTextField.text = type.document_name;
    
}

- (void)viewDidLoad
{
   // view.layer.borderWidth = 5.0f;
   // view.layer.borderColor = [[UIColor grayColor] CGColor];
//scrollView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"pw_maze_white.png"]];
    
    [self load_documentType];
    
    [[detailView layer] setBorderColor:[[UIColor lightGrayColor] CGColor]];
    [[detailView layer] setBorderWidth:2.3];
    [[detailView layer] setCornerRadius:15];
    [super viewDidLoad];
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed: @"22Navigation_background_320x46.png"]
                                                  forBarMetrics:UIBarMetricsDefault];
    
    UIButton *button1 = [[UIButton alloc] init];
    button1.frame= CGRectMake(0,0,43,32);
    [button1 setBackgroundImage:[UIImage imageNamed: @"bottom_home.png"] forState:UIControlStateNormal];
    
    [button1 addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:button1];
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
                                   initWithTarget:self
                                   action:@selector(dismissKeyboard)];
    
    [self.view addGestureRecognizer:tap];
    documentArray = [[NSMutableArray alloc] init];
    docTypesPickerArray = [[NSMutableArray alloc] init];
    
    [self load_documentType];
    
    
    UIToolbar* accessoryView = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
    accessoryView.barStyle = UIBarStyleBlackTranslucent;
    
    
    UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    
    UIBarButtonItem *done = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneTapped)];
    
    accessoryView.items = [NSArray arrayWithObjects:space,done, nil];
    
    docTypeTxt.inputAccessoryView = accessoryView;
    docTypeTxt.inputView = docTypePickerView;

    
	// Do any additional setup after loading the view.
}

-(void) load_documentType
{
    documentTypeArray = [[NSMutableArray alloc] init];
    
    
    NSString *url_str = [NSString stringWithFormat:@"http://www.aitproject.com/demo/webservice/public/service/document"];
    
    NSDictionary *publicTimeline =  jsonObjectFromUrlString(url_str);
    
    aDocTypeSheet = [[UIActionSheet alloc] initWithTitle:@"เลือกชนืดหลักฐาน" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil, nil];
    
    for(NSString *item in [publicTimeline allKeys]) {
        
        if([item isEqual: @"data"] )
        {
            NSDictionary *allData = [publicTimeline valueForKey:item];
            
            NSArray *allSue = [allData valueForKey:item];
            
            for(NSDictionary *data in allSue )
            {
                
                DocumentType* docType = [[DocumentType alloc] init];
                docType.document_id = [data valueForKey:@"Document_id"];
                docType.document_name = [data valueForKey:@"Document_Name"];
                docType.document_qty = [data valueForKey:@"Qty_Show"];
                docType.document_date = [data valueForKey:@"Date_Show"];
                
                [documentTypeArray addObject:docType];
                
                [aDocTypeSheet addButtonWithTitle:docType.document_name];

                
            }
        }
    }
    
    currentDocType = documentTypeArray[0];
}

-(void)dismissKeyboard {
    if(currentTextField != Nil)
        [currentTextField resignFirstResponder];
    
    if(currentTextView != Nil)
        [currentTextView resignFirstResponder];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
//    UILabel* tView = (UILabel*)view;
//    if (!tView){
//        tView = [[UILabel alloc] init];
//
//        // Setup label properties - frame, font, colors etc
//    }
//    // Fill the label text here
//    return tView;
//}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    currentTextField = textField;
    
    //UIPickerView* pickerView = (UIPickerView*)docTypesPickerArray[0];
    
    if(textField.tag == 9 || textField.tag == 102)
    {
        UIDocTypeTextField* docTypeField = (UIDocTypeTextField*)textField;
        currentDoc = documentArray[docTypeField.row];
        
        [docTypePickerView selectRow:currentDoc.Document_index inComponent:0 animated:NO];
        
        
        docTypePickerView.hidden = NO;
        
   
    }
    
    UIScrollView* v = (UIScrollView*) scrollView ;
    CGRect rc = [currentTextField bounds];
    rc = [currentTextField convertRect:rc toView:v];
    
    rc.origin.x = 0 ;
    rc.origin.y -= 60 ;
    
    rc.size.height = 400;
    [scrollView setContentOffset:CGPointMake(rc.origin.x, rc.origin.y)
                        animated:YES];
    
}

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    currentTextView = textView;
    
    UIScrollView* v = (UIScrollView*) scrollView ;
    CGRect rc = [currentTextView bounds];
    rc = [currentTextView convertRect:rc toView:v];
    
    rc.origin.x = 0 ;
    rc.origin.y -= 60 ;
    
    rc.size.height = 400;
    [scrollView setContentOffset:CGPointMake(rc.origin.x, rc.origin.y)
                        animated:YES];
}

- (BOOL)textView:(UITextView *)textView
shouldChangeTextInRange:(NSRange)range
 replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"])
    {
        [textView resignFirstResponder];
        
        [compName becomeFirstResponder];
    }
    return YES;
}

- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

{
    if ([string length] == 0 && range.length > 0)
    {
        return YES;
    }
    
    if (telText == textField  && [textField.text length] == 10)
    {
        [textField resignFirstResponder];
    }
    
    
    if ([string isEqualToString:@"\n"])
    {
        [textField resignFirstResponder];
    }
    
    
    NSCharacterSet* notDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
    if ([string rangeOfCharacterFromSet:notDigits].location != NSNotFound && (textField== telText) )
    {
        return NO;
    }
    
    return YES;
    
}

- (void)checkEmailAndDisplayAlert {
    if(![self validateEmail:[emailText text]]) {
        // user entered invalid email address
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Enter a valid email address."
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        emailText.text = @"";
    } else {
        // user entered valid email address
        
    }
}

- (BOOL)validateEmail:(NSString *)emailStr {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,10}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:emailStr];
}

- (void)sendFiles:(NSString*) complainId
{
    __block NSInteger nFile = [documentArray count];
    
    if(nFile == 0)
    {
        UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"แจ้งเบาะเเส"
                                                          message:[NSString stringWithFormat:@"เรื่องของท่านได้ถูกบันทึกเรียบร้อยแล้ว"]                                                       delegate:nil
                                                cancelButtonTitle:@"Close"
                                                otherButtonTitles:nil];
        [message show];
        
        [localSpiner stopAnimating];
        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed: @"New_Navigation_background_320x46.png"]
                                                      forBarMetrics:UIBarMetricsDefault];
        [self.navigationController popViewControllerAnimated:NO];
        
        


        
    }
    
    for(int i=0; i<[documentArray count]; i++)
    {
        Document* document = [documentArray objectAtIndex:i];
        
        NSString* urlstr = [NSString stringWithFormat:@"http://www.aitproject.com/demo/webservice/public/service/attach-file?Complain_id=%@&Document_id=%@",complainId,document.Document_id];
        
        NSString* doc_name = [NSString stringWithFormat:@"%@%d",document.Document_path,i];
        NSLog(@"ีurl = %@",urlstr);
        
        NSURL *url = [NSURL URLWithString:urlstr];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        
        [request setHTTPMethod:@"POST"];
        //[request setValue:authenKey forHTTPHeaderField:@"Authorization"];
        
        NSString *boundary = @"---------------------------14737809831466499882746641449";
        NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
        [request addValue:contentType forHTTPHeaderField:@"Content-Type"];
        
        //Add Form
        NSMutableData *body = [NSMutableData data];
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: attachment; name=\"file\";filename=\"%@\"\r\n", doc_name] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:document.imageData];
        [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        
        //Close Form
        [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [request setHTTPBody:body];
        
        [NSURLConnection sendAsynchronousRequest:request
                                           queue:[NSOperationQueue mainQueue]
                               completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                                   nFile--;
                                   NSLog(@"%@",data);
                                   NSString *returnstring=[[NSString alloc]initWithData:data encoding:NSASCIIStringEncoding];
                                   NSLog(@"%@",returnstring);
                                   
                                   NSDictionary* jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
                                   
                                   NSString* error_code = [jsonObject valueForKey:@"error_code"];
                                   
                                   if(error_code.intValue > 0)
                                   {
                                       UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"OCPB!"
                                                                                         message:[jsonObject valueForKey:@"message"]
                                                                                        delegate:nil
                                                                               cancelButtonTitle:@"OK"
                                                                               otherButtonTitles:nil];
                                       [message show];
                                       
                                   }
                                   else
                                   {

                                   }
                                   
                                   if (nFile == 0) {
                                       
                                       UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"แจ้งเบาะเเส"
                                                                                         message:[NSString stringWithFormat:@"เรื่องของท่านได้ถูกบันทึกเรียบร้อยแล้ว"]                                                       delegate:nil
                                                                               cancelButtonTitle:@"Close"
                                                                               otherButtonTitles:nil];
                                       [message show];
                                       
                                        [localSpiner stopAnimating];
                                       [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed: @"New_Navigation_background_320x46.png"]
                                                                                     forBarMetrics:UIBarMetricsDefault];
                                       [self.navigationController popViewControllerAnimated:NO];

                                       
                                   }
                               }
         
         ];
        
        
    }
}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    NSError *error = nil;
    //NSString *jsonResponse =  [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSDictionary* jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
    
    NSString* error_code = [jsonObject valueForKey:@"error_code"];
    
    
    NSString *jsonRequest =  [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    NSLog(@"jsonResponse is %@", jsonRequest);

    NSDictionary* complain_dict = [jsonObject valueForKey:@"data"];
    
    NSString* complainId = [complain_dict valueForKey:@"Complain_id"];
    
    if(error_code.intValue > 0)
    {
        UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"OCPB!"
                                                          message:[jsonObject valueForKey:@"message"]
                                                         delegate:nil
                                                cancelButtonTitle:@"OK"
                                                otherButtonTitles:nil];
        [message show];
        
    }
    else
    {
        [self sendFiles:complainId];
    }
    
}

- (IBAction)EndEdit:(id)sender {
    [self checkEmailAndDisplayAlert];
}

- (IBAction)delete_picture:(id)sender {
    
    UIDeleteButton *buttontag = (UIDeleteButton *)sender;
    //NSLog(@"%d",buttontag.tag);
    NSInteger Delete_row = buttontag.row;
    isDelete = true;
    [documentArray removeObjectAtIndex:Delete_row];
    [fileTable reloadData];
    

}

- (IBAction)makeClue:(id)sender {
    
    
    NSArray *objects;
    NSArray *keys;
    
    
    if([subjectText.text isEqual: @""] )
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"เเจ้งเบาะเเส" message:@"กรุณาใส่หัวข้อ"
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        
        return;
        
    }
    
    if([detailView.text isEqual: @""] )
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"เเจ้งเบาะเเส" message:@"กรุณาใส่รายละเอียด"
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        
        return;
        
    }
    
    
    
    

        objects = [NSArray arrayWithObjects:subjectText.text
                   , detailView.text
                   , telText.text
                   , emailText.text
                    , compName.text
                   ,nil];
        keys = [NSArray arrayWithObjects:@"Complain_Subject"
                ,@"Complain_Details"
                ,@"Petitioner_mobile"
                ,@"Petitioner_mail"
                ,@"Person_Comp_Name"
                ,nil];
        
    
    NSDictionary *jsonDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
    
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&error];
    
    
    NSString *jsonRequest = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    NSLog(@"jsonRequest is %@", jsonRequest);
    
    NSURL *url;
    
    url = [NSURL URLWithString:@"http://www.aitproject.com/demo/webservice/public/service/clue-report"];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    
    NSData *requestData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding]; //[NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
    
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];

    
    [request setHTTPBody: requestData];
    
    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
    
    
    CGPoint center = scrollView.contentOffset;
    
    center.x = localSpiner.center.x;
    
    center.y += 100;
    
    localSpiner.center = center;
   
   
    [localSpiner startAnimating];
    
    if (connection) {

    }
}

- (IBAction)selectDocType:(id)sender {
    
    UIActionSheet *asheet = aDocTypeSheet;
    
    currentDocButton = sender;
    
    [asheet setFrame:CGRectMake(0, 117, 320, 383)];
    
    [asheet showInView:[self.view superview]];
    
    
    UIScrollView* v = (UIScrollView*) scrollView ;
    CGRect rc = [sender bounds];
    rc = [sender convertRect:rc toView:v];
    
    rc.origin.x = 0 ;
    rc.origin.y -= 60 ;
    
    rc.size.height = 400;
    [scrollView setContentOffset:CGPointMake(rc.origin.x, rc.origin.y)
                        animated:YES];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //Get the name of the current pressed button
    
        
        UIDeleteButton *buttontag = (UIDeleteButton *)currentDocButton;
        NSInteger row = buttontag.row;
        
        currentDoc = documentArray[row];
        currentDocType = documentTypeArray[buttonIndex];
        currentDoc.Document_TypeName = currentDocType.document_name;
        [currentDocButton setTitle:currentDocType.document_name forState:UIControlStateNormal];
        currentDoc.Document_id = currentDocType.document_id;

    
    
}



- (IBAction)backAction:(id)sender {
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed: @"New_Navigation_background_320x46.png"]
                                                  forBarMetrics:UIBarMetricsDefault];
    
    [self.navigationController popViewControllerAnimated:NO];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    
    if(picker.sourceType == UIImagePickerControllerSourceTypeCamera )
    {
        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
    }
    
    NSData* imageData = UIImageJPEGRepresentation(image, 1.0);
    
    //NSString* incrementedImgStr = [NSString stringWithFormat: @"UserCustomPotraitPic%d.jpg", IMAGE_COUNTER];
    
    NSURL *imagePath = [info objectForKey:@"UIImagePickerControllerReferenceURL"];
    
    NSString *imageName = [imagePath path];
    
    NSArray *parts = [imageName componentsSeparatedByString:@"/"];
    NSString *filename = [parts objectAtIndex:[parts count]-1];
    
    NSLog(@"Image Path = %@",imageName);
    
    Document* doc = [[Document alloc] init];
    
    doc.Document_path = filename;
    doc.imageData = imageData;
    doc.Document_id = ((DocumentType*)documentTypeArray[0]).document_id;
    doc.Document_TypeName = ((DocumentType*)documentTypeArray[0]).document_name;
    doc.Document_index = 0;
    [picker dismissViewControllerAnimated:YES completion:NULL];
    [documentArray addObject:doc];
    isDelete = false;
    [fileTable reloadData];
    


    
    
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete ) {
        int row = indexPath.row;
        

        {
            [documentArray removeObjectAtIndex:row];
            [fileTable reloadData];
        }

    }
}



-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSInteger row = [documentArray count];
    
    return row;
}


-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    
    // Configure the cell...
    if (cell == nil)
    {
    }
    
    
    NSInteger row = indexPath.row;
    Document* doc = documentArray[row];
    UIImageView *fileimage = (UIImageView *)[cell viewWithTag:100];
    UIImage *img = [UIImage imageWithData:doc.imageData];
    fileimage.image = img;
    
    
    UIDeleteButton *deleteBtn = (UIDeleteButton *)[cell viewWithTag:101];
    deleteBtn.row = row;
    
    
    UIToolbar* accessoryView = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
    accessoryView.barStyle = UIBarStyleBlackTranslucent;
    
    
    UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    
    UIBarButtonItem *done = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneTapped)];
    
    accessoryView.items = [NSArray arrayWithObjects:space,done, nil];
    
    
    
    UIDeleteButton *fileType = (UIDeleteButton *)[cell viewWithTag:200];
    fileType.row = row;
    [fileType setTitle:doc.Document_TypeName forState:UIControlStateNormal];
    
    
    if(row == documentArray.count - 1 && isDelete == false)
        [fileType sendActionsForControlEvents: UIControlEventTouchUpInside];
    
    
    return cell;
    
}



- (void) imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:NULL];
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{    
    NSInteger row = [documentArray count];
    
    return row;
}


- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return YES if you want the specified item to be editable.
    return YES;
}

- (UITableViewCell *)tableView:(UITableView *)tableView1 cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView1 dequeueReusableCellWithIdentifier:CellIdentifier];
    
    // Configure the cell...
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    //cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    
    NSInteger row = indexPath.row;
    
    
  
    
    

    Document* doc = documentArray[row];
        
        
    UIImageView *fileimage = (UIImageView *)[cell viewWithTag:100];
    UIImage *img = [UIImage imageWithData:doc.imageData];
    fileimage.image = img;
    UIPickerView *doctypes = (UIPickerView *)[cell viewWithTag:103];
    doctypes.tag = row;
    

    
    
    return cell;
}



-(void)addCamera:(id)sender
{
    [currentTextField resignFirstResponder];
    [currentTextView resignFirstResponder];
    
    UIImagePickerController *imagePicker =
    [[UIImagePickerController alloc] init];
    
    imagePicker.delegate = self;
    
    imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    
    
    imagePicker.allowsEditing = NO;
    
    
    
    
    [self presentViewController:imagePicker animated:YES completion:NULL];
    
    [scrollView setContentOffset:CGPointMake(self.scrollView.contentOffset.x, 0)
                        animated:NO];
    
}

-(void)addPhotoLibrart:(id)sender
{
    [currentTextField resignFirstResponder];
    [currentTextView resignFirstResponder];
    
    UIImagePickerController *imagePicker =
    [[UIImagePickerController alloc] init];
    
    imagePicker.delegate = self;
    
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    
    imagePicker.allowsEditing = NO;
    
    
    
    [self presentViewController:imagePicker animated:YES completion:NULL];
    
}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath  {
    
    UICollectionViewCell *datasetCell =[collectionView cellForItemAtIndexPath:indexPath];
    datasetCell.backgroundColor = [UIColor blueColor]; // highlight selection
}

-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    UICollectionViewCell *datasetCell =[collectionView cellForItemAtIndexPath:indexPath];
    datasetCell.backgroundColor = [UIColor redColor]; // Default color
}


- (void)viewDidUnload {
    [self setFileTable:nil];
    [self setDocTypePickerView:nil];
    [self setFileTable:nil];
    [super viewDidUnload];
}
@end
